<script setup>
import { ref, computed, onUnmounted } from "vue";

const width = defineModel("width");

const props = defineProps({
  limit: {
    default: () => [200, 480],
  },
  type: {
    type: String,
    default: "left",
  },
});

const State = ref(false);

const Style = computed(() => {
  if (props.type == "left") {
    return { left: width.value - 3 + "px" };
  } else if (props.type == "right") {
    return { right: width.value - 3 + "px" };
  }
});

let CacheData = { Down: 0, Width: 0 };

const MouseMoveEvent = function (event) {
  const Relative = event.pageX - CacheData.Down;
  const min = Math.min.apply(this, props.limit);
  const max = Math.max.apply(this, props.limit);

  let MoveNumber;

  if (props.type == "left") {
    MoveNumber = CacheData.Width + Relative;
  } else if (props.type == "right") {
    MoveNumber = CacheData.Width - Relative;
  }

  if (MoveNumber < min) {
    width.value = min;
  } else if (MoveNumber > max) {
    width.value = max;
  } else {
    width.value = MoveNumber;
  }
};

let Dom = null;

const MouseUpEvent = function () {
  State.value = false;
  document.body.removeChild(Dom);
  Dom = null;
  window.removeEventListener("mousemove", MouseMoveEvent, true);
  window.removeEventListener("mouseup", MouseUpEvent, true);
};

const MouseDownEvent = function (event) {
  CacheData.Down = event.pageX;
  CacheData.Width = width.value;
  State.value = true;

  Dom = document.createElement("div");
  Dom.classList = ["MoveMark"];
  document.body.appendChild(Dom);

  window.addEventListener("mousemove", MouseMoveEvent, true);
  window.addEventListener("mouseup", MouseUpEvent, true);
};

// 组件执行时被以外注销，需要手动销毁组件
onUnmounted(() => {
  Dom && MouseUpEvent();
});
</script>
<template>
  <div
    class="MoveBar"
    :class="{ state: State }"
    @mousedown="MouseDownEvent"
    :style="Style"
  ></div>
</template>
<style scoped lang="less">
:global(.MoveMark) {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999999;
  cursor: e-resize;
}

.MoveBar {
  width: 5px;
  height: 100%;
  position: absolute;
  top: 0;
  cursor: e-resize;
  z-index: 10;
  &:hover {
    background-color: #aaa;
  }

  &.state {
    background-color: #ccc;
  }
}
</style>